package cn.xspace.wnx.fragment;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;

import com.xspace.android.xafcommon.base.BaseFragment;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.ErrorCode;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.PageUtil;
import com.xspace.android.xafcommon.util.T;
import com.xspace.android.xafcommon.view.XListView;
import com.xspace.android.xafcommon.view.dialog.ButtonClickListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.xspace.chatui.bean.MsgRecordEntity;
import cn.xspace.library.util.BldNavigation;
import cn.xspace.library.util.MsgType;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpManager;
import cn.xspace.wnx.R;
import cn.xspace.wnx.activity.ChatInfoActivity;
import cn.xspace.wnx.activity.GroupListActivity;
import cn.xspace.wnx.activity.MsgForwardActivity;
import cn.xspace.wnx.adapter.GroupAdapter;
import cn.xspace.wnx.entity.GroupEntity;
import cn.xspace.wnx.util.ForwardHelper;
import cn.xspace.wnx.util.Navigator;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by liuchen on 2016/10/31.
 */

public class GroupMineFragment extends BaseFragment {
    public static final String TAG = "GroupMineFragment";
    private XListView mListView;
    private int mGroupTyp;
    public static String KEY_TYPE = "group_type";
    private String user_id = "";
    Map<String, Object> dataMap = new HashMap<>();
    private SwipeRefreshLayout swipeRefreshLayout;
    private String url = "";
    private List<GroupEntity> dataList;
    private GroupAdapter mAdapter;
    private int lastItem;
    private MsgRecordEntity recordEntity;
//    View footView;

    @Override
    public View initView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_group_mine, null);
    }

    @Override
    protected void initFindViewById(View view) {
        mListView = (XListView) view.findViewById(R.id.listview_group);
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_layout);
        swipeRefreshLayout.setColorSchemeResources(R.color.holo_blue_bright, R.color.holo_green_light,
                R.color.holo_orange_light, R.color.holo_red_light);
    }

    @Override
    protected void getIntentData() {
        super.getIntentData();
        if (fragmentArgs != null) {
            recordEntity = (MsgRecordEntity) fragmentArgs.getSerializable(MsgForwardActivity.FORWARD_ENTITY);
        }

    }

    @Override
    public void initData() {
//        buildFootView();
//        mListView.addFooterView(footView);
//        footView.setVisibility(View.INVISIBLE);
        user_id = MyInfoUtil.getMyUserid(mContext);
        mGroupTyp = (Integer) fragmentArgs.get(KEY_TYPE);
        LogUtil.d("mGroupTyp>>" + mGroupTyp);
        if (mGroupTyp == GroupListActivity.GroupType.Normal.getNum()) {
            url = Constants.QUERY_USER_GROUP;
        } else if (mGroupTyp == GroupListActivity.GroupType.Organization.getNum()) {
            url = Constants.QUERY_USERORG_GROUP;
        } else if (mGroupTyp == GroupListActivity.GroupType.Professional.getNum()) {
            url = Constants.QUERY_PRO_GROUP;
        }
        dataList = new ArrayList<>();
        setadapter();
        requestNetwork();
//        swipeRefreshLayout.setRefreshing(true);
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                Log.d(TAG, "onScrollStateChanged() called with: view = [" + view + "], scrollState = [" + scrollState + "]" + "lastItem" + lastItem + "datalist size>>" + dataList.size());
                if (lastItem == dataList.size()
                        && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    LogUtil.d("addFooterView");
//                    mAdapter.notifyDataSetChanged();
//                    footView.setVisibility(View.VISIBLE);
//                    mListView.addFooterView(footView);
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                Log.i(TAG, "Scroll>>>first: " + firstVisibleItem
                        + ", visible: " + visibleItemCount + ", total: "
                        + totalItemCount);
                lastItem = firstVisibleItem + visibleItemCount;
                Log.i(TAG, "Scroll>>>lastItem:" + lastItem);
            }
        });
        mListView.setPullLoadEnable(true);
        mListView.setPullRefreshEnable(false);
        mListView.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                LogUtil.d("onRefresh");
            }

            @Override
            public void onLoadMore() {
                LogUtil.d("onLoadMore");
                mPageBean.page_index = getListMinIndex() + "";
                mPageBean.page_turn = PageUtil.PAGE_UP;
                mListView.stopLoadMore();
                requestNetwork();
            }
        });
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPageBean.page_index = getListMaxIndex() + "";
                requestNetwork();
            }
        });


        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG, "onItemClick() called with: , position = [" + position + "], id = [" + id + "]");
                final GroupEntity group = dataList.get(position - 1);

                if (recordEntity != null) {
                    ForwardHelper.getInstance().confirmBeforeForward(mContext, new ButtonClickListener() {
                        @Override
                        public void buttonClick(View view) {
                            ForwardHelper.getInstance().sendMessageGroup(mContext, recordEntity, group);
                        }
                    }, recordEntity, group.group_name);
                } else {
                    Bundle dataBundle = new Bundle();
                    dataBundle.putString(BldNavigation.SENDER_ID, group.group_id);
                    dataBundle.putInt(BldNavigation.CHAT_TYPE, MsgType.CHAT_CROUP.toNumber());
                    dataBundle.putString(BldNavigation.CHAT_NAME, group.group_name);
                    dataBundle.putString(BldNavigation.CHAT_SENDER_LOGO, group.group_logo);
                    dataBundle.putInt(BldNavigation.GROUP_TYPE, mGroupTyp);
                    dataBundle.putSerializable(MsgForwardActivity.FORWARD_ENTITY, recordEntity);
                    Navigator.startChatActivity(mContext, dataBundle);
                }

            }
        });

    }

    /**
     * 获取list的最小index
     *
     * @return
     */
    private int getListMinIndex() {
        int result = Integer.MAX_VALUE;
        for (GroupEntity entity : dataList) {
            if (entity.page_index < result) {
                result = entity.page_index;
            }
        }
        return result;
    }

    private int getListMaxIndex() {
        int result = Integer.MIN_VALUE;
        for (GroupEntity entity : dataList) {
            if (entity.page_index > result) {
                result = entity.page_index;
            }
        }
        return result;
    }

    private void buildFootView() {
//        footView = LayoutInflater.from(mContext).inflate(R.layout.listview_footer, null);
//        footView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                //加载更多
//                mPageBean.page_index = dataList.get(dataList.size() - 1).page_index;
//                mPageBean.page_turn = PageUtil.PAGE_UP;
//                requestNetwork();
//            }
//        });
//        mListView.addFooterView(footView);
    }

    private void requestNetwork() {
        dataMap.put("user_id", user_id);
        dataMap.put("pg", mPageBean);
        OkHttpManager.getInstance().commonRequest(url, dataMap)
                .subscribeOn(Schedulers.io())
                .map(new Func1<BaseReturnBean, List<GroupEntity>>() {
                    @Override
                    public List<GroupEntity> call(BaseReturnBean baseReturnBean) {
                        LogUtil.d(TAG, "wubaojie>>>call: 群组查询:" + baseReturnBean.data);
                        if (!ErrorCode.SUCCESS_CODE_WNX.equals(baseReturnBean.code)) {
                            T.showShort(mContext, R.string.network_error);
                            return null;
                        }
                        List<GroupEntity> datalist = new ArrayList<GroupEntity>();
                        try {
                            JSONArray jsonArray = new JSONArray(baseReturnBean.data);
                            for (int i = 0; i < jsonArray.length(); i++) {
                                GroupEntity entity = new GroupEntity();
                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                entity.group_name = jsonObj.optString("group_name");
                                entity.user_id = jsonObj.optString("user_id");
                                entity.user_name = jsonObj.optString("user_name");
                                entity.group_members = jsonObj.optInt("group_members");
                                entity.page_index = jsonObj.optInt("page_index");
                                entity.group_id = jsonObj.optString("group_id");
                                entity.group_theme = jsonObj.optString("group_desc");
                                entity.group_logo = jsonObj.optString("group_logo");
                                entity.group_ctime = jsonObj.optString("group_ctime");
                                entity.hx_groupid = jsonObj.optString("hx_groupid");
                                entity.group_type = mGroupTyp;
                                datalist.add(entity);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        return datalist;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe( new Subscriber<List<GroupEntity>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(List<GroupEntity> groupEntities) {
                        int getSize = groupEntities.size();
                        swipeRefreshLayout.setRefreshing(false);
                        LogUtil.d("dataSub>>" + getSize);
                        dataList.addAll(groupEntities);
                        setadapter();
                        if (getSize < PageUtil.PAGE_SIZE) {
                            mListView.setPullLoadEnable(false);
                        } else {
                            mListView.setPullLoadEnable(true);
                        }

                    }
                });
    }

//    Subscriber<List<GroupEntity>> dataSub =;

    private void setadapter() {
        LogUtil.i("worklog", "setadapter  mAdapter null:" + (mAdapter == null));
        if (dataList.size() == 0) {
//            img_work_log_no_content_tip.setVisibility(View.VISIBLE);
            mListView.setPullLoadEnable(false);
        } else {
//            img_work_log_no_content_tip.setVisibility(View.GONE);
        }
        if (mAdapter == null) {
            mAdapter = new GroupAdapter(mContext, dataList);
            mListView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }

    public static GroupMineFragment newInstance(int type) {
        Bundle args = new Bundle();
        GroupMineFragment fragment = new GroupMineFragment();

        args.putInt(KEY_TYPE, type);
        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onEventMainThread(Map<String, Object> inParam) {
        LogUtil.d(inParam.toString());
        super.onEventMainThread(inParam);
        if (TAG.equals(inParam.get(EventBusConstant.TYPE))) {
            if (ChatInfoActivity.GROUP_DELETE.equals(inParam.get(EventBusConstant.ACTION_KEY))) {
                LogUtil.d("delete group ");
                String groupId = (String) inParam.get(EventBusConstant.ACTION_VALUE);
                LogUtil.d("delete group groupId " + groupId);
                for (GroupEntity entity : dataList) {
                    if (entity.group_id.equals(groupId)) {
                        dataList.remove(entity);
                        mAdapter.notifyDataSetChanged();
                        break;
                    }
                }
            } else if (ChatInfoActivity.GROUP_NAME_CHANGE.equals(inParam.get(EventBusConstant.ACTION_KEY))) {
                GroupEntity groupEntity = (GroupEntity) inParam.get(EventBusConstant.ACTION_VALUE);
                if (groupEntity == null)
                    return;
                LogUtil.d("delete groupEntity groupId " + groupEntity.toString());
                for (GroupEntity entity : dataList) {
                    if (entity.group_id.equals(groupEntity.group_id)) {
                        entity.group_name = groupEntity.group_name;
                        mAdapter.notifyDataSetChanged();
                        break;
                    }
                }
            }
        } else if (EventBusConstant.FINISH_PAGE_FORWARD.equals(inParam.get(EventBusConstant.TYPE)) && recordEntity != null) {
            exitActivity2();
        }
    }
}
